package jsu.blogger.controller;

import jakarta.servlet.http.HttpServletRequest;
import jsu.blogger.pojo.Post;
import jsu.blogger.pojo.Result;
import jsu.blogger.service.impl.GetUserDataServiceImpl;
import jsu.blogger.service.impl.SystemNoticeService;
import jsu.blogger.service.inter.LiveService;
import jsu.blogger.util.ReturnResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController()
public class LiveController {
    @Autowired
    private LiveService liveService;
    @Autowired
    private GetUserDataServiceImpl getUserDataServiceImpl;
    private static final String BASE_PATH = "src/main/resources/static/livePhoto";
    private static final Logger log = LoggerFactory.getLogger(LiveController.class);

    @PostMapping("/live/publish")
    public Result publishLive(HttpServletRequest request) {
        try {
//            log.info("接收到动态发布请求");
            Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
            Long uid=Long.valueOf((Integer)map.get("uid"));
            Timestamp createdAt=convertStringToTimestamp((String) map.get("createdAt"));
            String text=(String)map.get("text");
            Long postId=liveService.insertOneLive(uid,createdAt,text);
            // 返回成功结果
            if(postId!=0L){
                return ReturnResultUtil.success(postId);
            }
            else
                return ReturnResultUtil.failure("动态发布失败");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ReturnResultUtil.failure(e.getMessage());
        }
    }
    @PostMapping("/img/uploadLivePhoto")
    public Result uploadLivePhoto(@RequestParam("livePhoto") MultipartFile livePhoto,
                                  @RequestParam("postId") Long postId,
                                  @RequestParam("index") int index) {
//        log.info("收到文件: " + livePhoto.getOriginalFilename());

        // 获取文件的后缀名
        String originalFilename = livePhoto.getOriginalFilename();
        String extension = originalFilename != null && originalFilename.contains(".") ?
                originalFilename.substring(originalFilename.lastIndexOf(".")) : "";

        // 生成新的文件名
        String newFileName = postId + "_" + (index+1) + extension;
        String currentDir = System.getProperty("user.dir");
        // 构建用户头像目录的相对路径
        File targetDir = new File(currentDir, BASE_PATH);
        // 创建文件路径
        if (!targetDir.exists()) {
            targetDir.mkdirs(); // 创建目录
        }
        File file = new File(targetDir, newFileName);

        try {
            // 将文件写入磁盘
            livePhoto.transferTo(file);
//            log.info("文件上传成功: " + file.getAbsolutePath());
            // 返回成功结果
            return ReturnResultUtil.success();
        } catch (IOException e) {
            log.error("文件上传失败: " + e.getMessage());
            liveService.deleteLiveByPostId(postId);
            return ReturnResultUtil.failure("文件上传失败");
        }
    }
    @PostMapping("/live/getLiveImg")
    public Result getLiveImg(@RequestBody Map<String, Long> request) {
        Long postId = request.get("postId");
        Long uid=request.get("uid");
        List<Map<String, String>> base64Images = new ArrayList<>(); // 包含后缀名的 Map
        Map<String, Object> reMap = new HashMap<>();
        Post post=liveService.selectOneLive(postId);
//        System.out.println("收到请求postId"+postId);
        if(post==null){
//            System.out.println("帖子不存在！");
            log.info("请求的动态不存在！");
            return ReturnResultUtil.failure("该帖子不存在！");
        }
        // 获取当前工作目录
        String currentDir = System.getProperty("user.dir");
        File targetDir = new File(currentDir, BASE_PATH);

        // 获取所有文件，按后缀过滤
        File[] files = targetDir.listFiles((dir, name) -> name.startsWith(postId + "_"));

        if (files != null) {
            for (File file : files) {
                try {
                    // 读取文件并转换为 Base64
                    byte[] fileContent = Files.readAllBytes(file.toPath());
                    String base64String = Base64Utils.encodeToString(fileContent);

                    // 获取文件后缀名
                    String fileName = file.getName();
                    String fileExtension = "";
                    int lastIndexOfDot = fileName.lastIndexOf('.');
                    if (lastIndexOfDot > 0 && lastIndexOfDot < fileName.length() - 1) {
                        fileExtension = fileName.substring(lastIndexOfDot + 1);
                    }

                    // 创建一个 Map 来保存 Base64 字符串和文件后缀名
                    Map<String, String> imageMap = new HashMap<>();
                    imageMap.put("base64", base64String);
                    imageMap.put("extension", fileExtension); // 保存文件后缀名

                    base64Images.add(imageMap);
                } catch (IOException e) {
                    log.error("读取文件失败: " + e.getMessage());
                    return ReturnResultUtil.failure("读取文件失败: " + e.getMessage());
                }
            }
        } else {
            log.warn("没有找到与 postId: " + postId + " 相关的图片");
        }
        HashMap<String,Object> map = new HashMap<>();
        reMap.put("base64Images", base64Images);
        return ReturnResultUtil.success(reMap);
    }
    @PostMapping("/live/getLiveContent")
    public Result getLiveContent(@RequestBody Map<String, Long> request) {
        Long postId = request.get("postId");
        Long uid=request.get("uid");
        Long writerUid=request.get("writerUid");
        Map<String, Object> reMap = new HashMap<>();
        Post post=liveService.selectOneLive(postId);
//        System.out.println("收到请求postId"+postId);
        if(post==null){
//            System.out.println("帖子不存在！");
            log.info("请求的动态不存在！");
            return ReturnResultUtil.failure("该帖子不存在！");
        }
        reMap.put("post",post) ;
        reMap.put("username",getUsername(writerUid));
        reMap.put("avatar",getUserAvatar(writerUid));
        reMap.put("isLike",liveService.isPostUserLike(postId,uid));
        reMap.put("likes",liveService.getPostLikes(postId));
        return ReturnResultUtil.success(reMap);
    }
    @PostMapping("/live/getLiveUserAvatar")
    public Result getLiveUserAvatar(@RequestBody Map<String, Long> request) {
        Long uid=request.get("uid");
        Map<String, Object> reMap = new HashMap<>();
        reMap.put("avatar",getUserAvatar(uid));
        return ReturnResultUtil.success(reMap);
    }
    @DeleteMapping("/live/deleteLive")
    public Result deleteLive(HttpServletRequest request) {
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        Long uid=Long.valueOf((Integer)map.get("uid"));
        Long postId=Long.valueOf((Integer)map.get("postId"));
        // 检查动态是否存在
        Post post = liveService.selectOneLive(postId);
        if (post == null) {
            log.info("请求的动态不存在！");
            return ReturnResultUtil.failure("该帖子不存在！");
        }

        // 检查用户是否有权限删除该动态
        if (post.getUserId()!=uid) {
            log.warn("用户没有权限删除该动态！");
            return ReturnResultUtil.failure("您没有权限删除该动态！");
        }

        // 删除动态内容
        boolean isDeleted = liveService.deleteLiveByPostId(postId);
        if (!isDeleted) {
            log.error("删除动态失败，postId: " + postId);
            return ReturnResultUtil.failure("删除动态失败，请稍后再试！");
        }

        // 删除相关的图片文件
        String currentDir = System.getProperty("user.dir");
        File targetDir = new File(currentDir, BASE_PATH);
        File[] files = targetDir.listFiles((dir, name) -> name.startsWith(postId + "_"));

        if (files != null) {
            for (File file : files) {
                if (!file.delete()) {
                    log.warn("删除文件失败: " + file.getName());
                }
            }
        }
        log.info("用户"+uid+"删除了动态"+postId);
        return ReturnResultUtil.success("动态删除成功！");
    }
    @GetMapping("/live/getRecommendLive/{userId}/{begin}/{cnt}")
    public Result getRecommendLive(@PathVariable String userId,@PathVariable String begin,@PathVariable String cnt) {
        Long uid=Long.valueOf(userId);
        int count=Integer.parseInt(cnt);
        int offset=Integer.parseInt(begin);
        List<Map> lists= new ArrayList<>();
        List<Post> posts=liveService.selectLiveLimit(offset,count);
        posts.forEach(post->{
            Map<String,Object> map = new HashMap<>();
            List<Map<String, String>> base64Images = getLivePhoto(post.getPostId(),0);
            String username=getUsername(post.getUserId());
            map.put("base64Images", base64Images);
            map.put("post", post);
            map.put("username", username);
            map.put("avatar",getUserAvatar(post.getUserId()));
            lists.add(map);
        });
//        if(uid==-1L){//说明用户没有登录，是一个未登录uid
//            //推送遍历的帖子
//
//        }
////        这是处理推荐帖子的控制器
////        首先，前端会发送一个用户uid，也就是我们需要针对这个uid，推送他感兴趣的内容，还有一个参数，是控制发送的帖子个数
////        对于推送，我们针对性的推送该用户关注的对象发送的动态，且发送时间越晚，权重越高，发送时间越旧，就越不推送
////        所以，第一步，查找该用户的关注列表，然后对关注的用户进行随机查找推送
//        List<Long> follows=liveService.selectFollowedUid(uid);
//        follows.forEach(follow-> System.out.println("用户uid:"+uid+"关注了uid:"+follow));
////        第二部，查询关注列表中
//        return ReturnResultUtil.success(follows);
        return ReturnResultUtil.success(lists);
    }
    @GetMapping("/live/getMyLive/{userId}/{begin}/{cnt}")
    public Result getMyLive(@PathVariable String userId,@PathVariable String begin,@PathVariable String cnt) {
        Long uid=Long.valueOf(userId);
        int count=Integer.parseInt(cnt);
        int offset=Integer.parseInt(begin);
        List<Map> lists= new ArrayList<>();
        List<Post> posts=liveService.selectLiveByUid(uid,offset,count);
        posts.forEach(post->{
            Map<String,Object> map = new HashMap<>();
            List<Map<String, String>> base64Images = getLivePhoto(post.getPostId(),1);
            String username=getUsername(post.getUserId());
            map.put("base64Images", base64Images);
            map.put("post", post);
            lists.add(map);
        });
        return ReturnResultUtil.success(lists);
    }
    @GetMapping("/live/like/{postId}/{uid}")
    public Result like(@PathVariable Long postId,@PathVariable Long uid) {
        if(liveService.isPostUserLike(postId,uid)!=null){
            return ReturnResultUtil.failure("该用户已经点过赞了");
        }
        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
        if(liveService.addLiveLike(postId,uid,1,timestamp)){
            SystemNoticeService.noticeLiveLike(uid,liveService.getUserIdByPostId(postId),postId,getUserDataServiceImpl.getUsernameByUserId(uid),liveService.getLiveContent(postId),timestamp);
            return ReturnResultUtil.success();
        }
        return ReturnResultUtil.failure("点赞失败");
    }
    @GetMapping("/live/cancelLike/{postId}/{uid}")
    public Result cancelLike(@PathVariable Long postId,@PathVariable Long uid) {
        if(liveService.isPostUserLike(postId,uid)==null){
            return ReturnResultUtil.failure("该用户还没有给这篇帖子点过赞");
        }
        if(liveService.deleteLiveLike(postId,uid)){
            return ReturnResultUtil.success();
        }
        return ReturnResultUtil.failure("取消点赞失败");
    }

    public List<Map<String, String>> getLivePhoto(Long postId,int order){
        List<Map<String, String>> base64Images = new ArrayList<>();
        String currentDir = System.getProperty("user.dir");
        File targetDir = new File(currentDir, BASE_PATH);

        // 获取所有文件，按后缀过滤
        File[] files = targetDir.listFiles((dir, name) -> name.startsWith(postId + "_"));

        if (files != null) {
            int numberOfImagesToReturn = 0;

            // 根据 files.length 确定返回图片的数量
            if(files.length <= 4) {
                numberOfImagesToReturn = 1;
            } else if (files.length >= 5 && files.length <= 9) {
                numberOfImagesToReturn = 2;
            }
            if(order==1){
                numberOfImagesToReturn = 1;
            }
            // 只处理需要返回的数量的图片
            for (int i = 0; i < Math.min(numberOfImagesToReturn, files.length); i++) {
                File file = files[i];
                try {
                    // 读取文件并转换为 Base64
                    byte[] fileContent = Files.readAllBytes(file.toPath());
                    String base64String = Base64Utils.encodeToString(fileContent);

                    // 获取文件后缀名
                    String fileName = file.getName();
                    String fileExtension = "";
                    int lastIndexOfDot = fileName.lastIndexOf('.');
                    if (lastIndexOfDot > 0 && lastIndexOfDot < fileName.length() - 1) {
                        fileExtension = fileName.substring(lastIndexOfDot + 1);
                    }

                    // 创建一个 Map 来保存 Base64 字符串和文件后缀名
                    Map<String, String> imageMap = new HashMap<>();
                    imageMap.put("base64", base64String);
                    imageMap.put("extension", fileExtension); // 保存文件后缀名

                    base64Images.add(imageMap);
                } catch (IOException e) {
                    log.error("读取文件失败: " + e.getMessage());
                }
            }
        } else {
            log.warn("没有找到与 postId: " + postId + " 相关的图片");
        }

        return base64Images;
    }

    public static Timestamp convertStringToTimestamp(String dateString) {
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析字符串为 LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(dateString, formatter);

        // 转换为时间戳（毫秒）
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return Timestamp.from(instant);
    }

    public String getUsername(Long userId){
        String username=null;
        if(userId!=null){
            username= getUserDataServiceImpl.getUsernameByUserId(userId);
        }
        return username;
    }
    private  Map<String,Object> getUserAvatar(Long uid){
        File userAvatar=getUserDataServiceImpl.getUserAvatar(uid);
        Map<String,Object> reMap=new HashMap<>();
        if(userAvatar!=null){
            try{
                String imgType="data:image/"+this.getFileExtension(userAvatar)+";";
                // 将文件内容读取为字节数组
                byte[] fileContent = Files.readAllBytes(userAvatar.toPath());
                // 将字节数组编码为 Base64 字符串
                String base64String = Base64.getEncoder().encodeToString(fileContent);

                reMap.put("imgType",imgType);
                reMap.put("userAvatar",base64String);
            } catch (IOException e) {
                log.error(String.valueOf(e));
            }
        }
        return reMap;
    }
    private String getFileExtension(File file) {
        // 确保传入的是有效的文件对象
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("文件不存在或无效");
        }
        // 获取文件名
        String fileName = file.getName();

        // 找到最后一个点的位置
        int lastDotIndex = fileName.lastIndexOf('.');

        // 如果没有点，返回空字符串
        if (lastDotIndex == -1) {
            return "";
        }
        // 提取后缀名并转换为小写
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }
}